package com.sunlei.webtest.quickstart.fanoutexchange;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
 * @Author: sun
 * @Description:
 * @Data: create in 17:43 2018/11/22
 * @Modfied by:
 */

public class FanoutConsumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        System.out.println("-----Fanout Exchange Consumer strat-----");
        // 1.创建一个connectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        // 2.通过连接工厂创建连接
        Connection connection =  connectionFactory.newConnection();
        // 3.通过connection创建channel
        Channel channel = connection.createChannel();
        // 4.声明Exchange
        final String exchangeName = "test_fanout_exchange";
        final String exchageType = "fanout";
        final String queueName = "test_fanout_queue";
        final String routeKey = "";
        channel.exchangeDeclare(exchangeName,exchageType,true,false,false,null);
        channel.queueDeclare(queueName,true,false,false,null);
        channel.queueBind(queueName,exchangeName,routeKey);
        // 5.创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        // 6.设置channel
        channel.basicConsume(queueName,true,queueingConsumer);
        // 7.获取消息
        while (true){
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("[Fanout Exchange获取消息]:"+msg);
        }
        // 5.记得记得关闭连接
//        channel.close();
//        connection.close();
    }
}
